/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kungkhies.persistence.kungkher;

import com.kungkhies.domain.kungkher.Kungkher;
import com.kungkhies.domain.kungkhie.KungkhieSummary;
import java.util.List;
import com.kungkhies.persistence.entities.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.metamodel.Metamodel;
import javax.transaction.*;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author clayton
 */
@Repository
public class JpaKungkherDaoImpl implements KungkherDao
{
//    private EntityManager entityManager;
    
    
    private EntityManagerFactory entityManagerFactory;
   
    
    public JpaKungkherDaoImpl(){}
    
    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory)
    {
        this.entityManagerFactory = entityManagerFactory;
    }

//    @PersistenceContext
//    public void setEntityManager(EntityManager entityManager)
//    {
//        this.entityManager = entityManager;
//    }

    @Override
    @Transactional
    public void addKungkher(com.kungkhies.domain.kungkher.Kungkher kungkher)
    {

        com.kungkhies.persistence.entities.Kungkher kungk = new com.kungkhies.persistence.entities.Kungkher();

//        kungk.setKungkherId(null);
//        kungk.setDateRegistered(kungkher.getDateRegistered());
        kungk.setEmail(kungkher.getEmail());
        kungk.setFullname(kungkher.getFullName());
        kungk.setInterests(kungkher.getInterests());
        kungk.setPassword(kungkher.getPassword());
        kungk.setUsername(kungkher.getKungkherName());

        EntityManager entityManager = entityManagerFactory.createEntityManager();

        if (entityManager == null)
        {
            System.out.println("EntityManager is NULL in KungkherDaoImpl");
        }
        else
        {
            System.out.println("EntityManager is NOT NULL in KungkherDaoImpl");
        }
        try
        {
            entityManager.getTransaction().begin();
            entityManager.persist(kungk);
            entityManager.getTransaction().commit();

        }
        catch (ConstraintViolationException e)
        {
            Set viols = (HashSet) e.getConstraintViolations();

            Iterator it = viols.iterator();

            while (it.hasNext())
            {
                ConstraintViolation cv = (ConstraintViolation) it.next();
                System.out.println("Constraint property path: " + cv.getPropertyPath());
                System.out.println("Constraint violaton descriptor: " + cv.getConstraintDescriptor());
                System.out.println("Constraint violaton message: " + cv.getMessage());
                //System.out.println(cv.getInvalidValue());
            }
        }
        finally
        {
            entityManager.close();
        }
        //commit transaction which will trigger the em to 
        //commit newly created entity into database



    }

    @Override
    @Transactional
    public void saveKungkher(Kungkher kungkher)
    {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        
        try
        {
            entityManager.getTransaction().begin();
            com.kungkhies.persistence.entities.Kungkher kungk = entityManager.find(com.kungkhies.persistence.entities.Kungkher.class, kungkher.getId());
            kungk.setFullname(kungkher.getFullName());
            kungk.setInterests(kungkher.getInterests());
            kungk.setUsername(kungkher.getKungkherName());
            kungk.setPassword(kungkher.getPassword());
            kungk.setEmail(kungkher.getEmail());

            entityManager.getTransaction().commit();
        }
        catch (ConstraintViolationException e)
        {
            Set viols = (HashSet) e.getConstraintViolations();

            Iterator it = viols.iterator();

            while (it.hasNext())
            {
                ConstraintViolation cv = (ConstraintViolation) it.next();
                System.out.println("Constraint property path: " + cv.getPropertyPath());
                System.out.println("Constraint violaton descriptor: " + cv.getConstraintDescriptor());
                System.out.println("Constraint violaton message: " + cv.getMessage());
                //System.out.println(cv.getInvalidValue());
            }
        }
        finally
        {
            entityManager.close();
        }
    }

    @Override
    public Kungkher getKungkherById(long id)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<KungkhieSummary> getRecentKungkhies()
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void saveKungkhie(KungkhieSummary kungkhie)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<KungkhieSummary> getKungkhiesForKungkher(Kungkher kungkher)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Kungkher getKungkherByUsername(String username)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void deleteKungkhie(long id)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public KungkhieSummary getKungkhieById(long id)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Kungkher> findAllKungkhers()
    {
        List<com.kungkhies.domain.kungkher.Kungkher> kungkherList = new ArrayList<com.kungkhies.domain.kungkher.Kungkher>();
        List<com.kungkhies.persistence.entities.Kungkher> kungkherEntityList = null;
        EntityManager entityManager = entityManagerFactory.createEntityManager();

        if (entityManager == null)
        {
            System.out.println("EntityManager is NULL in KungkherDaoImpl");
        }
        else
        {
            System.out.println("EntityManager is NOT NULL in KungkherDaoImpl");
        }
        try
        {
            //com.kungkhies.persistence.entities.Kungkhie kungkhie = new com.kungkhies.persistence.entities.Kungkhie();
            entityManager.getTransaction().begin();
            Query query = entityManager.createNamedQuery("Kungkher.findAll", com.kungkhies.persistence.entities.Kungkher.class);
            
            kungkherEntityList = query.getResultList();
            entityManager.getTransaction().commit();

        }
        finally
        {
            entityManager.close();
        }
        
        
        
        for (com.kungkhies.persistence.entities.Kungkher kungkherEntity : kungkherEntityList)
        {
            com.kungkhies.domain.kungkher.Kungkher kungkher = new com.kungkhies.domain.kungkher.Kungkher();
            kungkher.setFullName(kungkherEntity.getFullname());
            kungkher.setKungkherName(kungkherEntity.getUsername());
            kungkher.setEmail(kungkherEntity.getEmail());
            kungkher.setInterests(kungkherEntity.getInterests());
            kungkher.setDateRegistered(kungkherEntity.getDateRegistered());
            kungkher.setUpdateByEmail(false);
            
            kungkherList.add(kungkher);
        }
        
        return kungkherList;
    }

    @Override
    @Transactional
    public boolean kungkherNameExists(String kungkherName)
    {
        //There might be a better way to do this.  Here if the getSingleResult()
        //throws a NoResultExpcetion is no result is returned.  This is caught and
        //used as proof that a kungkher with that kungkherName does not
        //exist.
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        try
        {
            entityManager.getTransaction().begin();
            try
            {
                com.kungkhies.persistence.entities.Kungkher kungkhers = (com.kungkhies.persistence.entities.Kungkher) entityManager.createNamedQuery("Kungkher.findByUsername").setParameter("username", kungkherName).getSingleResult();
                entityManager.getTransaction().commit();
            }
            catch (NoResultException nre)
            {
                //kungkherName does not exist;
                return false;
            }
        }
        finally
        {
            entityManager.close();
        }
   
        //kungkherName exists
        return true;

    }

    @Override
    public boolean emailAddressExists(String emailAddress)
    {
        //There might be a better way to do this.  Here if the getSingleResult()
        //throws a NoResultExpcetion is no result is returned.  This is caught and
        //used as proof that a kungkher with that kungkherName does not
        //exist.
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        
        try
        {
            entityManager.getTransaction().begin();
            try
            {
                com.kungkhies.persistence.entities.Kungkher kungkhers = (com.kungkhies.persistence.entities.Kungkher) entityManager.createNamedQuery("Kungkher.findByEmail").setParameter("email", emailAddress).getSingleResult();
                entityManager.getTransaction().commit();
                
            }
            catch (NoResultException nre)
            {
                //email address does not exist;
                return false;
            }
        }
        finally
        {
            entityManager.close();
        }
   
        //email address exists
        return true;
    }
  
}
